//
//  ChildViewController.m
//  Village
//
//  Created by 程虎 on 2017/9/7.
//  Copyright © 2017年 程虎. All rights reserved.
//

#import "ChildViewController.h"
#import "HeadLineDetailsController.h"
#import "YZDisplayViewHeader.h"
#import "HomeHttpTools.h"
#import "ChildViewCell.h"
#import "VillageModel.h"
#import "TTHttpTools.h"
#import "RequesCover.h"
#import "ChildModel.h"

@interface ChildViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, weak) RequesCover *cover;
@property (nonatomic, strong) NSMutableArray *dataAry;
@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageCount;//总页数 
@end

@implementation ChildViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageNum = 1;
    self.pageCount = 0;
    
    self.tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H - kNavHeight - 49) style:UITableViewStyleGrouped];
    self.tabView.delegate = self;
    self.tabView.dataSource = self;
    self.tabView.showsVerticalScrollIndicator = NO;
    self.tabView.showsHorizontalScrollIndicator = NO;
    self.tabView.estimatedRowHeight = UITableViewAutomaticDimension;
    self.tabView.estimatedSectionFooterHeight = UITableViewAutomaticDimension;
    self.tabView.estimatedSectionHeaderHeight = 0;
    self.tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tabView.backgroundColor = [Util colorWithHexString:@"f7f7f7"];
    [self.view addSubview:self.tabView];
    
    if (@available(iOS 11.0, *)) {
        self.tabView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    self.tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshheader_data)];
    
    self.tabView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshfoot_data)];
    [self.tabView registerNib:[UINib nibWithNibName:@"ChildViewCell" bundle:nil] forCellReuseIdentifier:@"ChildViewCell"];
    
    /****滚动完成请求数据*******/
    
    // 如果想要滚动完成或者标题点击的时候，加载数据，需要监听通知
    
    // 监听滚动完成或者点击标题，只要滚动完成，当前控制器就会发出通知
    
    // 只需要监听自己发出的，不需要监听所有对象发出的通知，否则会导致一个控制器发出，所有控制器都能监听,造成所有控制器请求数据
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:YZDisplayViewClickOrScrollDidFinshNote object:self];
    
//    if (self.navigationController) {
//        // 导航条上面高度
//        CGFloat navBarH = 64;
//        
//        // 查看自己标题滚动视图设置的高度，我这里设置为44
//        CGFloat titleScrollViewH = 44;
//        
//        self.tabView.contentInset = UIEdgeInsetsMake(navBarH + titleScrollViewH, 0, 0, 0);
//    }
//    
//    // 如果有tabBarController，底部需要添加额外滚动区域
//    self.tabView.contentInset = UIEdgeInsetsMake(64 + 44, 0, 49, 0);
    
    // 开发中可以搞个蒙版，一开始遮住当前界面，等请求成功，在把蒙版隐藏.
    RequesCover *cover = [RequesCover requestCover];
    
    [self.view addSubview:cover];
    
    _cover = cover;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(childLoginRefresh) name:RefreshLoginInfo object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:RefreshLoginInfo object:nil];
}

#pragma mark - 登录、更新用户信息刷新
- (void)childLoginRefresh
{
    [self refreshheader_data];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.cover.frame = self.view.bounds;
}

// 加载数据
- (void)loadData
{
    NSLog(@"%@ -- %ld 请求数据成功",self.title,[self getControllerIndex]);
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        for (int i = 0; i  < [Globle getInstance].headlineArys.count; i++) {
//            NSDictionary *dict = [Globle getInstance].headlineArys[i];
//            NSDictionary *dict1 = PostedTypeAry[[self getControllerIndex]];
//            if ([dict[@"code3"] isEqualToString:dict1[@"code3"]]) {
//                [self.dataAry addObject:[VillageModel mj_objectArrayWithKeyValuesArray:dict[@"news"]]];
//            }
//        }
//
//    });

    self.pageNum = 1;
    [self getdata:0];
}

#pragma mark - 下拉刷新
- (void)refreshheader_data
{
    self.pageNum = 0;
    self.pageCount = 0;
    [self.tabView.mj_footer setState:MJRefreshStateIdle];
    [self getdata:0];
}

#pragma mark - 上拉刷新
- (void)refreshfoot_data
{
    self.pageNum += 1;
    if (self.pageNum < self.pageCount + 1) {
        [self getdata:self.pageNum];
    }
    else {
        [EmptyFunction hideEmpty:self.tabView];
        [self.tabView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - TableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataAry.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildViewCell *cell = [ChildViewCell cellWithTableView:tableView];
    cell.model = self.dataAry[indexPath.section];
    cell.shareBlock = ^(VillageModel *model) {
        [self shareWithModel:model];
    };
    cell.shareBtn.hidden = YES;
    [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *views = [UIView new];
    views.backgroundColor = [Util colorWithHexString:@"f7f7f7"];
    return views;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self addReadNum:self.dataAry[indexPath.section]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Class currentClass = [ChildViewCell class];
    return [self.tabView cellHeightForIndexPath:indexPath model:self.dataAry[indexPath.section] keyPath:@"model" cellClass:currentClass contentViewWidth:SCREEN_W];
}

#pragma mark - 获取数据
- (void)getdata:(NSInteger )index
{
    NSDictionary *dict = PostedTypeAry[[self getControllerIndex]];
    WeakSelf(weakSelf);
    [TTHttpTools GetNewsWithPageNum:index WithCode:dict[@"code3"] Success:^(NSDictionary *valueDict) {
        
        if (index == 0) {
            [weakSelf.tabView.mj_header endRefreshing];
            self.pageCount = [valueDict[@"pagecount"] integerValue];
            self.dataAry = [NSMutableArray array];
            self.dataAry = [VillageModel mj_objectArrayWithKeyValuesArray:valueDict[@"list"]];
        }
        else {
            [weakSelf.tabView.mj_footer endRefreshing];
            NSArray *array = self.dataAry;
            self.dataAry = [NSMutableArray arrayWithArray:array];
            [self.dataAry addObjectsFromArray:[VillageModel mj_objectArrayWithKeyValuesArray:valueDict[@"list"]]];
        }
//        [self cacheHeadline:[VillageModel mj_keyValuesArrayWithObjectArray:self.dataAry] Type:dict[@"code3"]];
        [EmptyFunction hideEmpty:self.tabView];
        [self.cover removeFromSuperview];
        [weakSelf.tabView reloadData];
    } failure:^(NSString *error) {
        [self.cover removeFromSuperview];
        
        if (index == 0) {
            [weakSelf.tabView.mj_header endRefreshing];
        }
        else {
            [weakSelf.tabView.mj_footer endRefreshing];
        }
        [EmptyFunction showEmpty:self.tabView Height:(self.tabView.frame.size.height - self.tabView.tableHeaderView.height)];
    }];
}

#pragma mark - 增加阅读数
- (void)addReadNum:(VillageModel *)model
{
    WeakSelf(weakSelf);
    [MBProgressHUD showMessage:@"正在加载..." toView:self.navigationController.view];
    [HomeHttpTools AddHeadlineNewReadNumWith:model Success:^() {
        [MBProgressHUD hideHUDForView:self.navigationController.view];
        [Tools ToNextName:@"HeadLineDetailsController" Params:model CurrentVC:weakSelf Completion:^(id obj) {
            
        }];
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUDForView:self.navigationController.view];
    }];
}

#pragma mark - 分享
- (void)shareWithModel:(VillageModel *)model
{
    [ShareFunction shareInstance].titles = @"村居通";
    [ShareFunction shareInstance].content = model.title;
    [ShareFunction shareInstance].iconImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[Tools resolutionHeadImage:model.upimg]]]];
    [ShareFunction shareInstance].url = model.shareurl;
    [[ShareFunction shareInstance] shareToController:self];
}

#pragma mark - 缓存数据
- (void)cacheHeadline:(NSArray *)array Type:(NSString *)type
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *datas = [NSMutableArray array];
        [datas addObjectsFromArray:[Globle getInstance].headlineArys];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:type forKey:@"code3"];
        [dict setObject:array forKey:@"news"];
        if (datas.count) {
            for (int i = 0; i < datas.count; i++) {
                NSDictionary *dict1 = datas[i];
                if ([dict1[@"code3"] isEqualToString:type]) {
                    [datas replaceObjectAtIndex:i withObject:dict];
                }
                else {
                    [datas addObject:dict];
                }
            }
        }
        else {
            [datas addObject:dict];
        }
        
        [[Globle getInstance] saveHeadline:datas];
    });
}

#pragma mark - 判断下标
- (NSInteger )getControllerIndex
{
    NSInteger index = 0;
    if ([self.title isEqualToString:@"农村生活"]) {
        index = 0;
    }
    else if ([self.title isEqualToString:@"情感交友"]) {
        index = 1;
    }
    else if ([self.title isEqualToString:@"致富有道"]) {
        index = 2;
    }
    else if ([self.title isEqualToString:@"特产美食"]) {
        index = 3;
    }
    else if ([self.title isEqualToString:@"农村旅游"]) {
        index = 4;
    }
    else if ([self.title isEqualToString:@"劳务信息"]) {
        index = 5;
    }
    else if ([self.title isEqualToString:@"寻人寻物"]) {
        index = 6;
    }
    
    return index;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded] && self.view.window == nil) {
        self.view = nil;
    }
    self.dataAry = nil;
}
@end
